<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
		<style>
			html,
			body,
			#container {
				width: 100%;
				height: 100%;
			}
		</style>
		<title>航线展示</title>
		<script src="https://webapi.amap.com/maps?v=2.0&key=ce77626588b7a2ee836159f48dd4a1a6&plugin=AMap.PolygonEditor"></script>
		<script src="https://webapi.amap.com/loca?v=2.0&key=ce77626588b7a2ee836159f48dd4a1a6"></script>
	</head>
	<body>
		<div id="container"></div>
		<script type="text/javascript">
			// 初始化高德地图
			var map = new AMap.Map("container", {
				center: [120.140001, 30.250001], // 地图中心点
				zoom: 15, // 缩放级别
				pitch: 60, // 倾斜角度
				viewMode: '3D', // 3D视图模式
			});

			// 初始化Loca容器
			var loca = new Loca.Container({
				map: map,
			});

			var lineLayer = new Loca.LineLayer({
				loca: loca,
				zIndex: 100,
			});
			lineLayer.setSource(new Loca.GeoJSONSource({
				data: {
					type: 'FeatureCollection',
					features: [],
				},
			}));
			lineLayer.setStyle({
				altitude: true,
				lineWidth: 3,
				color: '#3366FF',
				opacity: 0.8,
			});

			let lineData = []; // 存储线数据
			let markers = []; // 存储标记点

			// 将经纬度保留到小数点后8位
			function roundTo8Decimals(num) {
				return Number(num.toFixed(8));
			}

			// 加载JSON文件
			function loadJSON(file, callback) {
				fetch(file)
					.then(response => response.json())
					.then(data => callback(data))
					.catch(error => console.error('加载JSON文件失败:', error));
			}

			// 设置标记点的高度
			function render_marker_height(marker) {
				marker.on('positionUpdate', function() {
					var altitude = this.getExtData().altitude || 80;
					this.setPosition([this.getPosition().lng, this.getPosition().lat, altitude]);
				});
				marker.emit('positionUpdate');
			}

			// 生成并绘制航线
			function generateAndDrawPath() {
				// 清空现有线和标记
				lineData = [];
				markers.forEach(marker => map.remove(marker));
				markers = [];

				// 加载边框数据（仅用于参考，不绘制边框）
				loadJSON('bk.json', function(borderData) {
					const borderPoints = borderData.map(point => ({
						longitude: point.longitude,
						latitude: point.latitude,
						height: point.height
					}));
					function convertPoints(inputData) {
					    return inputData.map(point => [
					        Number(point.longitude.toFixed(8)),
					        Number(point.latitude.toFixed(8)),
					    ]);
					}
					var polygon2 = new AMap.Polygon({
						path: convertPoints(borderPoints),
						strokeColor: "#FF33FF",
						strokeWeight: 2,
						fillColor: "#1791fc",
						fillOpacity: 0.35
					});
					map.add(polygon2);
					map.setFitView(polygon2);

					// 加载航点数据
					loadJSON('hd.json', function(waypointData) {
						const waypoints = waypointData.map(point => ({
							longitude: roundTo8Decimals(point.longitude),
							latitude: roundTo8Decimals(point.latitude),
							height: point.height
						}));

						// 如果航点数据为空，提示并退出
						if (waypoints.length === 0) {
							alert('航点数据为空，请检查FeHelper2.json文件');
							return;
						}

						// 生成线数据
						for (let i = 0; i < waypoints.length - 1; i++) {
							lineData.push({
								type: 'Feature',
								geometry: {
									type: 'LineString',
									coordinates: [
										[waypoints[i].longitude, waypoints[i].latitude, waypoints[i].height],
										[waypoints[i + 1].longitude, waypoints[i + 1].latitude, waypoints[i + 1].height]
									]
								}
							});
						}

						// // 添加标记点
						waypoints.forEach((point, index) => {
							const marker = new AMap.Marker({
								position: [point.longitude, point.latitude],
								offset: new AMap.Pixel(-10, -10),
								content: `<div style="background-color: red; color: white; padding: 2px 6px; border-radius: 3px; font-size: 12px; user-select: none;">${index + 1}</div>`,
								zIndex: 101,
								extData: {
									altitude: point.height,
								}
							});
							map.add(marker);
							render_marker_height(marker);
							markers.push(marker);
						});

						// 渲染线图层
						lineLayer.setSource(new Loca.GeoJSONSource({
							data: {
								type: 'FeatureCollection',
								features: lineData,
							},
						}));
						lineLayer.render();

						// 调整地图视角以适应所有标记点
						map.setFitView(markers);
						console.log('航点:', waypoints);
					});
				});
			}

			// 页面加载时生成并绘制航线
			generateAndDrawPath();
		</script>
	</body>
</html>